package com.suray.rgv60.task;

import com.suray.basic.wcs.utils.LoggerType;
import com.suray.basic.wcs.utils.WcsFuncUtil;
import com.suray.rgv.util.RgvLogger;

import java.util.ArrayList;
import java.util.List;

/**
 * 完成任务管理
 */
public class EndTaskManage {
    /**
     * 10分钟后删除任务
     */
    private final long DELETE_TICK = 10 * 60 * 1000;

    /**
     * 最大保存任务个数
     */
    private final int MAX_END_TASK_SIZE = 20;

    private List<EndTaskContainer> endTasks;

    public EndTaskManage() {
        endTasks = new ArrayList<>();
    }

    /**
     * 检测任务是否已完成
     * @param taskId
     * @return
     */
    public boolean isTaskEnd(Object taskId) {
        for (EndTaskContainer endTask : endTasks) {
            if (endTask.task.getTaskId().equals(taskId)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 添加完成任务
     * @param task
     * @param endTime
     */
    public void addEndTask(TaskInfo task, Long endTime) {
        RgvLogger.info(LoggerType.END_RGV_TASK, task.getTaskId(), null,
                task.toString(), this.getClass());
        if (endTasks.size() > MAX_END_TASK_SIZE) {
            endTasks.remove(0);
        }
        endTasks.add(new EndTaskContainer(task, endTime));
    }

    /**
     * 清理过时的完成任务
     */
    public void analyzeEndTasks() {
        long currentTime = System.currentTimeMillis();
        List<EndTaskContainer> overdueTasks = new ArrayList<>();

        endTasks.forEach(endTask -> {
            if ((currentTime - endTask.endTime) > DELETE_TICK) {
                overdueTasks.add(endTask);
            }
        });

        if (overdueTasks.size() > 0) {
            RgvLogger.info(LoggerType.DELETE_RGV_TASK, null, null,
                    WcsFuncUtil.listToString(overdueTasks), this.getClass());
            endTasks.removeAll(overdueTasks);
        }
    }

    class EndTaskContainer {
        TaskInfo task;
        long endTime;

        EndTaskContainer(TaskInfo task, Long endTime) {
            this.task = task;
            this.endTime = endTime;
        }

        @Override
        public String toString() {
            return "EndTaskContainer{" +
                    "task=" + task +
                    ", endTime=" + endTime +
                    '}';
        }
    }
}
